//extern crate fast_common;

use actix_http::KeepAlive;

use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::dev::Service;
use actix_web::http::header;
use actix_web::middleware::{ErrorHandlerResponse, Logger};
use actix_web::{App, HttpServer};
use env_logger::{Builder, Env};
use log::LevelFilter;

use fast_common::common::orm_config::{InitDb, RB};
use fast_common::middleware;
use fast_common::middleware::cors::CorsConfig;

mod controller;
mod routers;
mod service;
mod storage;

fn init_logger() {
    std::env::set_var("RUST_LOG", "actix_web=debug");
    let env =
        Env::default().filter_or("RUST_LOG", "DEBUG").write_style_or("MY_LOG_STYLE", "always");
    Builder::from_env(env)
        .filter_level(LevelFilter::Debug)
        .format_level(true)
        .format_timestamp_micros()
        .init();
}

async fn init_db_link() {
    let _ =
        RB.link_opt("postgres://postgres:postgres@127.0.0.1:5432/test", InitDb::db_option()).await;
}

fn _add_error_header<B>(
    mut res: actix_web::dev::ServiceResponse<B>,
) -> actix_web::Result<ErrorHandlerResponse<B>> {
    res.response_mut()
        .headers_mut()
        .insert(header::CONTENT_TYPE, header::HeaderValue::from_static("Error"));
    Ok(ErrorHandlerResponse::Response(res.map_into_left_body()))
}

async fn _hello() -> &'static str {
    println!("执行hello方法");
    "hello,world"
}

fn policy() -> CookieIdentityPolicy {
    let policy = CookieIdentityPolicy::new(&[0; 1024]).name("authorization").secure(false);
    return policy;
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    init_logger();
    init_db_link().await;
    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .wrap(middleware::handle_method::HandleMethod)
           // .wrap(middleware::auth::Authorization)
            .wrap_fn(|req, srv| {
                let ret = srv.call(req);
                async { ret.await }
            })
            // .wrap(CorsConfig::cors_config())

            .wrap(IdentityService::new(policy()))
            .configure(routers::index_route::index_routers)
            .configure(routers::user_route::user_routers)
            .configure(routers::role_route::role_routers)
            .configure(routers::menu_route::menu_routes)
    })
    .keep_alive(KeepAlive::Os)
    .bind("127.0.0.1:3000")?
    .run()
    .await
}
